// src/services/topics.js - 话题社区服务

import { get, post } from './api';

// 本地存储key
const TOPICS_STORAGE_KEY = 'starrypt_topics';
const TOPIC_POSTS_STORAGE_KEY = 'starrypt_topic_posts';

// 初始化本地存储数据
export const initTopicsData = () => {
  if (!localStorage.getItem(TOPICS_STORAGE_KEY)) {
    localStorage.setItem(TOPICS_STORAGE_KEY, JSON.stringify([]));
  }
  if (!localStorage.getItem(TOPIC_POSTS_STORAGE_KEY)) {
    localStorage.setItem(TOPIC_POSTS_STORAGE_KEY, JSON.stringify([]));
  }
};

// 本地存储操作
const localGetTopics = () => {
  return JSON.parse(localStorage.getItem(TOPICS_STORAGE_KEY) || '[]');
};

const localGetTopicPosts = (topicId = null) => {
  const posts = JSON.parse(localStorage.getItem(TOPIC_POSTS_STORAGE_KEY) || '[]');
  return topicId ? posts.filter(post => post.topicId === topicId) : posts;
};

const localCreateTopic = (topicData) => {
  const topics = localGetTopics();
  const newTopic = {
    id: Date.now(),
    ...topicData,
    createTime: new Date().toISOString(),
    posts: 0,
    members: 1
  };
  topics.push(newTopic);
  localStorage.setItem(TOPICS_STORAGE_KEY, JSON.stringify(topics));
  return { success: true, topic: newTopic };
};

const localCreateTopicPost = (topicId, postData) => {
  const posts = localGetTopicPosts();
  const newPost = {
    id: Date.now(),
    topicId: topicId,
    ...postData,
    createTime: new Date().toISOString(),
    likes: 0,
    replies: 0,
    views: 0
  };
  posts.push(newPost);
  localStorage.setItem(TOPIC_POSTS_STORAGE_KEY, JSON.stringify(posts));
  return { success: true, post: newPost };
};

/**
 * 获取话题列表
 * @returns {Promise} - 话题列表
 */
export const getTopics = async () => {
  try {
    const response = await get('/topics/list');

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data
      };
    } else {
      return {
        success: false,
        message: response.message || '获取话题列表失败'
      };
    }
  } catch (error) {
    console.warn('获取话题列表API连接失败，使用本地存储:', error);

    const topics = localGetTopics();
    return {
      success: true,
      data: { topics }
    };
  }
};

/**
 * 获取话题详情
 * @param {number} topicId - 话题ID
 * @returns {Promise} - 话题详情
 */
export const getTopicDetail = async (topicId) => {
  try {
    const response = await get(`/topics/${topicId}`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data
      };
    } else {
      return {
        success: false,
        message: response.message || '获取话题详情失败'
      };
    }
  } catch (error) {
    console.warn('获取话题详情API连接失败，使用本地存储:', error);

    const topics = localGetTopics();
    const topic = topics.find(t => t.id === parseInt(topicId));

    if (!topic) {
      throw new Error('话题不存在');
    }

    return {
      success: true,
      data: { topic }
    };
  }
};

/**
 * 创建新话题
 * @param {Object} topicData - 话题数据
 * @returns {Promise} - 创建结果
 */
export const createTopic = async (topicData) => {
  try {
    const response = await post('/topics', topicData);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data,
        message: response.message
      };
    } else {
      return {
        success: false,
        message: response.message || '创建话题失败'
      };
    }
  } catch (error) {
    console.warn('创建话题API连接失败，使用本地存储:', error);

    const result = localCreateTopic(topicData);
    if (result.success) {
      return {
        success: true,
        message: '话题创建成功',
        data: { topic: result.topic }
      };
    } else {
      throw new Error(result.message || '创建话题失败');
    }
  }
};

/**
 * 获取话题内的帖子
 * @param {number} topicId - 话题ID
 * @param {Object} params - 查询参数
 * @returns {Promise} - 帖子列表
 */
export const getTopicPosts = async (topicId, params = {}) => {
  try {
    const query = new URLSearchParams();
    if (params.page) query.append('page', params.page);
    if (params.limit) query.append('limit', params.limit);
    if (params.type) query.append('type', params.type);

    const queryString = query.toString();
    const endpoint = queryString ? `/topics/${topicId}/allPosts?${queryString}` : `/topics/${topicId}/allPosts`;

    const response = await get(endpoint);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data
      };
    } else {
      return {
        success: false,
        message: response.message || '获取话题帖子失败'
      };
    }
  } catch (error) {
    console.warn('获取话题帖子API连接失败，使用本地存储:', error);

    const posts = localGetTopicPosts(topicId);

    // 应用筛选
    let filteredPosts = posts;
    if (params.type) {
      filteredPosts = posts.filter(post => post.type === params.type);
    }

    // 排序（置顶优先，然后按时间）
    filteredPosts.sort((a, b) => {
      if (a.isSticky && !b.isSticky) return -1;
      if (!a.isSticky && b.isSticky) return 1;
      return new Date(b.createTime) - new Date(a.createTime);
    });

    // 简单分页
    const page = params.page || 1;
    const limit = params.limit || 20;
    const start = (page - 1) * limit;
    const end = start + limit;
    const paginatedPosts = filteredPosts.slice(start, end);

    return {
      success: true,
      data: {
        posts: paginatedPosts,
        total: filteredPosts.length,
        page: page,
        limit: limit
      }
    };
  }
};

/**
 * 获取话题内的单个帖子详情
 * @param {number} topicId - 话题ID
 * @param {number} postId - 帖子ID
 * @returns {Promise} - 帖子详情
 */
export const getTopicPostDetail = async (topicId, postId) => {
  try {
    const response = await get(`/topics/${topicId}/${postId}`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data
      };
    } else {
      return {
        success: false,
        message: response.message || '获取帖子详情失败'
      };
    }
  } catch (error) {
    console.warn('获取帖子详情API连接失败，使用本地存储:', error);

    const post = getTopicPostById(postId);
    if (!post) {
      throw new Error('帖子不存在');
    }

    // 增加浏览量
    increasePostViewCount(postId);

    return {
      success: true,
      data: { post }
    };
  }
};

/**
 * 在话题内发布帖子
 * @param {number} topicId - 话题ID
 * @param {Object} postData - 帖子数据
 * @returns {Promise} - 发布结果
 */
export const createTopicPost = async (topicId, postData) => {
  try {
    const response = await post(`/topics/${topicId}/posts`, postData);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data,
        message: response.message
      };
    } else {
      return {
        success: false,
        message: response.message || '发布帖子失败'
      };
    }
  } catch (error) {
    console.warn('发布帖子API连接失败，使用本地存储:', error);

    const result = localCreateTopicPost(topicId, postData);
    if (result.success) {
      return {
        success: true,
        message: '帖子发布成功',
        data: { post: result.post }
      };
    } else {
      throw new Error(result.message || '发布帖子失败');
    }
  }
};

/**
 * 点赞话题内的帖子
 * @param {number} postId - 帖子ID
 * @returns {Promise} - 点赞结果
 */
export const likeTopicPost = async (postId) => {
  try {
    const response = await post(`/topics/posts/${postId}/like`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data,
        message: response.message || '操作成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '点赞失败'
      };
    }
  } catch (error) {
    console.warn('点赞帖子API连接失败:', error);
    throw new Error('点赞帖子失败: ' + error.message);
  }
};

/**
 * 加入话题
 * @param {number} topicId - 话题ID
 * @returns {Promise} - 加入结果
 */
export const joinTopic = async (topicId) => {
  try {
    const response = await post(`/topics/${topicId}/join`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data,
        message: response.message || '加入成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '加入失败'
      };
    }
  } catch (error) {
    console.warn('加入话题API连接失败:', error);
    throw new Error('加入话题失败: ' + error.message);
  }
};

/**
 * 删除话题内的帖子 (管理员功能)
 * @param {number} topicId - 话题ID
 * @param {number} postId - 帖子ID
 * @returns {Promise} - 删除结果
 */
export const deleteTopicPost = async (topicId, postId) => {
  try {
    const response = await post(`/topics/${topicId}/posts/delete/${postId}`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        message: response.message || '删除成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '删除失败'
      };
    }
  } catch (error) {
    console.warn('删除帖子API连接失败:', error);
    throw new Error('删除帖子失败: ' + error.message);
  }
};

/**
 * 删除话题 (拥有者功能)
 * @param {number} topicId - 话题ID
 * @returns {Promise} - 删除结果
 */
export const deleteTopic = async (topicId) => {
  try {
    const response = await post(`/topics/delete/${topicId}`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        message: response.message || '话题删除成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '话题删除失败'
      };
    }
  } catch (error) {
    console.warn('删除话题API连接失败:', error);
    throw new Error('删除话题失败: ' + error.message);
  }
};

/**
 * 添加话题管理员
 * @param {number} topicId - 话题ID
 * @param {number} userId - 用户ID
 * @returns {Promise} - 添加结果
 */
export const addTopicAdmin = async (topicId, userId) => {
  try {
    const response = await post(`/topics/${topicId}/admins/add/${userId}`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        message: response.message || '管理员添加成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '管理员添加失败'
      };
    }
  } catch (error) {
    console.warn('添加管理员API连接失败:', error);
    throw new Error('添加管理员失败: ' + error.message);
  }
};

/**
 * 移除话题管理员
 * @param {number} topicId - 话题ID
 * @param {number} userId - 用户ID
 * @returns {Promise} - 移除结果
 */
export const removeTopicAdmin = async (topicId, userId) => {
  try {
    const response = await post(`/topics/${topicId}/admins/remove/${userId}`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        message: response.message || '管理员移除成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '管理员移除失败'
      };
    }
  } catch (error) {
    console.warn('移除管理员API连接失败:', error);
    throw new Error('移除管理员失败: ' + error.message);
  }
};

/**
 * 置顶/取消置顶帖子
 * @param {number} topicId - 话题ID
 * @param {number} postId - 帖子ID
 * @returns {Promise} - 置顶操作结果
 */
export const pinTopicPost = async (topicId, postId) => {
  try {
    const response = await post(`/topics/${topicId}/posts/${postId}/pin`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        message: response.message || '置顶操作成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '置顶操作失败'
      };
    }
  } catch (error) {
    console.warn('置顶帖子API连接失败:', error);
    throw new Error('置顶帖子失败: ' + error.message);
  }
};

// 辅助函数
const getTopicPostById = (postId) => {
  const posts = localGetTopicPosts();
  return posts.find(post => post.id === parseInt(postId));
};

const increasePostViewCount = (postId) => {
  const posts = localGetTopicPosts();
  const postIndex = posts.findIndex(post => post.id === parseInt(postId));
  if (postIndex !== -1) {
    posts[postIndex].views = (posts[postIndex].views || 0) + 1;
    localStorage.setItem(TOPIC_POSTS_STORAGE_KEY, JSON.stringify(posts));
  }
};

const topicsService = {
  initTopicsData,
  getTopics,
  getTopicDetail,
  createTopic,
  getTopicPosts,
  getTopicPostDetail,
  createTopicPost,
  likeTopicPost,
  joinTopic,
  deleteTopicPost,
  deleteTopic,
  addTopicAdmin,
  removeTopicAdmin,
  pinTopicPost
};

export default topicsService;